﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public static class CFileSystem
{
    public static string BaseDir = Application.streamingAssetsPath;
    public static string BackupBaseDir = Application.streamingAssetsPath;
    public static string ReadStringFile(string path, string baseDir = null, string backUpDir = null)
    {
        string _baseDir = string.IsNullOrEmpty(baseDir) ? BaseDir : baseDir;
        string filePath = string.Format("{0}/{1}", _baseDir, path);
        if (!File.Exists(filePath))
        {
            _baseDir = string.IsNullOrEmpty(backUpDir) ? BackupBaseDir : backUpDir;
            filePath = string.Format("{0}/{1}", _baseDir, path);
        }

        string content = string.Empty;
#if UNITY_ANDROID  && ! UNITY_EDITOR
        UnityWebRequest www =  UnityWebRequest.Get(filePath); 
        www.SendWebRequest();
        while (!www.isDone)
        {
            //wait file load completed
        }

        if ( null != www.error)
            Debug.LogError(string.Format("Failed FILE {0} {1} {2}", path, filePath, www.error));
        else
            content = www.downloadHandler.text;
#else
        if (System.IO.File.Exists(filePath))
            content = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
        else
            content = string.Empty;
#endif
        return content;
    }

    public static byte[] ReadBinaryFile(string path, string baseDir = null, string backUpDir = null)
    {
        string _baseDir = string.IsNullOrEmpty(baseDir) ? BaseDir : baseDir;
        string filePath = string.Format("{0}/{1}", _baseDir, path);
        if (!File.Exists(filePath))
        {
            _baseDir = string.IsNullOrEmpty(backUpDir) ? BackupBaseDir : backUpDir;
            filePath = string.Format("{0}/{1}", _baseDir, path);            
        }
        // CLog.Log(string.Format("load bin file {0}", filePath));
        byte[] content = null;
#if UNITY_ANDROID && !UNITY_EDITOR    
        //if (filePath.Contains("://"))
        {
            UnityWebRequest www = UnityWebRequest.Get(filePath);
            www.SendWebRequest();                        
            while (!www.isDone)
            {   
            }
            if (www.error == null)
                content = www.downloadHandler.data;
            else
                Debug.LogError(string.Format("Failed FILE {0} {1} {2}", path, filePath, www.error));       
        }
        {
            try
            {
                content = System.IO.File.ReadAllBytes(filePath);
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                return null;
            }
        }
#endif
        return content;
    }

}






